package com.baichuan.zntx.service;

import com.baichuan.zntx.domain.Device;
import com.baichuan.zntx.domain.Region;
import com.baichuan.zntx.domain.Task;
import com.baichuan.zntx.rules.*;
import lombok.AllArgsConstructor;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DeviceRulesService {
    private final DefaultRulesEngine rulesEngine;
    @Autowired
    private IMessageService messageService;
    public DeviceRulesService() {
        this.rulesEngine = new DefaultRulesEngine();
    }

    public void evaluateDevice(Device device, Region region, Task task) {
        // 创建 Facts 对象并传入设备对象
        Facts facts = new Facts();
        facts.put("device", device);
        if(region!=null){
            facts.put("region", region);
        }
        if(task!=null){
            facts.put("task", task);
        }

        // 创建规则集
        Rules rules = new Rules();

        // 低电量报警规则
        rules.register(new LowBatteryRule(messageService));

        if (device.getStatus()==0) {
            // 如果设备处于工作状态，添加防溜报警规则
            rules.register(new AntiSlipRule(messageService));
            // 非法拆除报警规则
            rules.register(new IllegalRemovalRule(messageService));
        }
        if(task!=null && task.getStatus()!=2){
            // 注册任务超时报警规则
            rules.register(new TimeoutRule(messageService));
        }
        if(region!=null){
            // 注册防盗报警规则
            rules.register(new AntiTheftRule(messageService));
        }
        // 执行规则
        rulesEngine.fire(rules, facts);
    }
}
